package com.lagou.util;

import com.lagou.bean.ExecTime;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;

/**
 * 队列指标统计
 */
public class Statistics implements Runnable {

    private LinkedList<ExecTime> queue;
    private String methodName;

    public Statistics(LinkedList<ExecTime> queue,String methodName) {
        this.queue = queue;
        this.methodName=methodName;
    }
    LinkedList<Long> longs;
    int count=0;

    public void run() {
        count++;
        //System.out.println("第"+count+"次调用");
        longs = new LinkedList<Long>();
        //当前时间点
        long nowtime = System.currentTimeMillis();
        long minuteBefore = nowtime - 60000;//1分钟之前
        long wwBefore = nowtime - 55000;//55秒之前

        Iterator<ExecTime> it = queue.iterator();
        while (it.hasNext()){
            ExecTime et = it.next();
            long pts = et.getTimestamp();
            long etime = et.getExectime();
            if(pts < minuteBefore){ //元素超过一分钟之前
                it.remove();
                //System.out.println("直接扔掉的数据："+et.toString());
            }else if(minuteBefore <=pts && pts < wwBefore){ //60秒到55秒之间的
                longs.add(etime);
                it.remove();
                //System.out.println("取出并放到集合的数据："+et.toString());
            }else if(wwBefore <= pts && pts < nowtime){//55s到现在的只查看放入set,队列中保留
                longs.add(etime);
                //System.out.println("只放到集合的数据："+et.toString());
            }else{//大于等于现在停止这一轮
                //System.out.println("本轮完毕");
                break;
            }
        }
        Collections.sort(longs);
        //String format = String.format("%s 一分钟中内请求数为：%d \n前100个数据为 %s",methodName,longs.size(),longs.toString());
        int _90 = (int)(longs.size() * 0.90);
        int _99 = (int)(longs.size() * 0.99);

        String format = String.format("%s %d次统计 | 分钟请求 %d 次 | tp90 ==> %d | tp99 ==> %d",methodName,count,longs.size(),longs.get(_90),longs.get(_99));
        System.out.println(format);
    }
}
